#
#===============================================================================
#
#         FILE:  Weather.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/14/2010 10:57:08 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::Weather;

use LWP::UserAgent;
use JSON qw(decode_json);
use URI::Escape qw(uri_escape);

sub register {
    my $self = shift;

    return ('cmd' => 'weather', 'pat' => '^!?weather\s+(.*)');
}

sub help {
    my $self = shift;
    return ('Get current weather information via Google weather. For best results, search on city, state or zipcode');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    $msgtxt =~ /^weather\s+(.*)/;
    my $loc = $1;

    my $geoloc_url = "http://where.yahooapis.com/v1/places.q('".uri_escape($loc)."')?appid=bHbLpWnV34GMU1g3AOS7E.mn_XRyPH5isu9qErTcmkTch_TTUaiIfZEX7KDfq0c-&format=json";

    my $ua = LWP::UserAgent->new;
    my $r = $ua->get($geoloc_url);
    my $json = decode_json($r->decoded_content);

    if (!defined($json->{'places'}) || $json->{'places'}{'count'} == 0) {
	$kernel->post($sender => privmsg => $target => "$loc not found");
	return;
    }
    my $lat = $json->{'places'}{'place'}[0]{'centroid'}{'latitude'};
    my $lon = $json->{'places'}{'place'}[0]{'centroid'}{'longitude'};
    my $woeid = $json->{'places'}{'place'}[0]{'woeid'};

    my $wsql = "select * from weather.forecast where woeid=$woeid and u='f'";
    my $weather_url = "http://query.yahooapis.com/v1/public/yql?q=".uri_escape($wsql)."&format=json";
    
    $r = $ua->get($weather_url);
    my $wjson = decode_json($r->decoded_content);
    
    if (!defined($wjson->{'query'}{'results'})) {
	$kernel->post($sender => privmsg => $target => "weather forecast not found");
	return;
    }

    $kernel->post($sender => privmsg => $target =>
	    sprintf('Current for %s: %s %sF(%dC), Humidity %s%%, Wind %s, High of %sF, Low of %sF',
		    $json->{'places'}{'place'}[0]{'locality2'}||$json->{'places'}{'place'}[0]{'locality1'},
		    $wjson->{'query'}{'results'}{'channel'}{'item'}{'condition'}{'text'},
		    $wjson->{'query'}{'results'}{'channel'}{'item'}{'condition'}{'temp'},
		    ($wjson->{'query'}{'results'}{'channel'}{'item'}{'condition'}{'temp'} - 32) * 5/ 9,
		    $wjson->{'query'}{'results'}{'channel'}{'atmosphere'}{'humidity'},
		    $wjson->{'query'}{'results'}{'channel'}{'wind'}{'speed'},
		    $wjson->{'query'}{'results'}{'channel'}{'item'}{'forecast'}[0]{'high'},
		    $wjson->{'query'}{'results'}{'channel'}{'item'}{'forecast'}[0]{'low'}
		));
    return;
}

1;
